<template>
    <div>
        <el-form ref="formSku" size="small" label-width="100px" :rules="rules" :model="sku">
             <el-form-item label="SPU名称">
                  {{spu.spuName}}
             </el-form-item>
             <el-form-item label="SKU名称" prop="skuName">
                  <el-input  placeholder="输入SKU名称" v-model="sku.skuName" ></el-input>
             </el-form-item>
             <el-form-item label="价格(元)" prop="price">
                  <el-input  placeholder="价格(元)" v-model.number="sku.price"></el-input>
             </el-form-item>
             <el-form-item label="重量(千克)" prop="weight" >
                  <el-input  placeholder="重量(千克)" v-model.number="sku.weight" type="number"></el-input>
             </el-form-item>
             <el-form-item label="规格描述" prop="skuDesc">
                  <el-input type="textarea" rows="4" placeholder="规格描述" v-model="sku.skuDesc"></el-input>
             </el-form-item>
             <el-form-item label="平台属性" >
                  <el-form :inline="true" ref="form" label-width="80px" size="small">
                     <el-form-item :label="attr.attrName" v-for="(attr) in attrInfoList" :key="attr.id" >
                        <el-select  placeholder="请选择" v-model="attr.attrIdAndValueId" >
                            <el-option v-for="(item) in attr.attrValueList" :key="item.id" :label="item.valueName" :value="`${attr.id}:${item.id}`" ></el-option>
                        </el-select>
                     </el-form-item>
                  </el-form>
             </el-form-item>
             <el-form-item label="销售属性">
                  <el-form :inline="true" ref="form" label-width="80px" size="small">
                     <el-form-item v-for="(saleAttr) in saleAttrList"  :key="saleAttr.id"  :label="saleAttr.saleAttrName">
                        <el-select  placeholder="请选择" v-model="saleAttr.saleAttrIdAndSaleAttrValueId">
                        <el-option v-for="(saleAttrValue) in saleAttr.spuSaleAttrValueList" :key="saleAttrValue.id"  :label="saleAttrValue.saleAttrValueName" :value="`${saleAttr.id}:${saleAttrValue.id}`"></el-option>
                        </el-select>
                     </el-form-item>
                  </el-form>
             </el-form-item>
             <el-form-item label="图片列表">
                <el-table style="width:100%" border  @selection-change="handleSelectionChange"  :data="imageList" >
                    <el-table-column type="selection" width="55" align="center" >
                    </el-table-column>
                    <el-table-column prop="prop" label="图片" width="width">
                        <template v-slot:default="{row}">
                            <div style="width: 80px;height: 80px;">
                                <img :src="row.imgUrl" alt="" style="width:100%;">
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="imgName" label="名称" width="width">
                    </el-table-column>
                    <el-table-column prop="prop" label="操作" width="width">
                        <template v-slot:default="{row,$index}">
                            <el-button type="primary" size="mini" @click="setDefaultImage(row,$index)" v-if="!row.isDefault">设为默认值</el-button>
                            <el-button v-else type="success"  size="mini" plain disabled>默认</el-button>
                        </template>
                    </el-table-column>
                </el-table>
             </el-form-item>
             <el-form-item style="margin-top: 18px;">
                <el-button type="primary"  @click="addOrUpdateSku">保存</el-button>
                <el-button  @click="cancelSelect">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>

export default {
    name:'SkuForm',
    data(){
      return {
        rules: {
            skuName: [
              { required: true, message: '请输入Sku名称', trigger: 'blur' },
            ],
            price: [
              { required: true, message: '请输入价格', trigger: 'blur' },
              { type: 'number', message: '价格必须为数字值'}
            ],
            weight:[
              { required: true, message: '请输入重量', trigger: 'blur' },
              { type: 'number', message: '价格必须为数字值'}
            ],
            skuDesc:[
              { required: true, message: '请输入规格描述', trigger: 'blur' },
            ],
            attrIdAndValueId:[
              { required: true, message: '请选择平台属性', trigger: 'change' },
            ]
          },
        spu:'',
        sku:{
            //第一类收集的数据：父组件给的数据
            "category3Id": '',
            "spuId": '',
             tmId: '', 
            //第二类收集的数据： v-model收集的数据
            "skuName": "",
            "price":'',
            //默认显示图片  
            "skuDefaultImg": "",
            //商品规格描述
            "skuDesc": "",
            //商品的重量
            "weight":'',
            //收集sku属性值
            "skuAttrValueList": [
                  /* {
                      "attrId": '',
                      "valueId": '',
                  } */
              ],
              // 收集Sku图片信息
              "skuImageList": [
                    /*{   
                      "imgName": "",
                      "imgUrl": "",
                      "isDefault": "",
                      "spuImgId":''
                  } */
              ],
               //收集sku销售属性值
              "skuSaleAttrValueList": [
                  /* {
                      "saleAttrId": '',
                      "saleAttrValueId": '',
                  } */
              ],
          },
        //存储图片的信息
        imageList :[],
        //存放销售属性
        saleAttrList:[], 
        //存储平台属性的数据
        attrInfoList:[],
        //存储复选框选中的数据，但是需要注意，当前收集的数据当中，缺少isDefault字段，将来提交数据时需要整理参数
        multipleSelection: []
      }
    },
    methods:{
        async getData(spu, categoryids) {
            //收集父组件给的数据
            this.sku.category3Id = spu.category3Id
            this.sku.spuId = spu.id
            this.sku.tmId = spu.tmId
            this.spu = spu
            //解构各级分类的id
            const { category1ID, category2ID, category3ID } = categoryids
            //1.获取图片的数据
            const imageResult = await this.$API.sku.reqSpuImageList(spu.id)
            if (imageResult.code == 200) {
                let list = imageResult.data;
                list.forEach(item=>{
                    item.isDefault = 0;
                })
                this.imageList = list;
            }
            //2.获取销售属性信息
            const saleAttrResult = await this.$API.sku.reqSaleAttrList(spu.id)
            if (saleAttrResult.code == 200) {
                this.saleAttrList = saleAttrResult.data
            }
            //3.根据产品分类id获取商品基础数据
            const attrInfoListResult = await this.$API.sku.reqAttrInfoList(category1ID, category2ID, category3ID)
            if (attrInfoListResult.code == 200) {
                this.attrInfoList = attrInfoListResult.data
            }
        },
        // 取消事件
        cancelSelect() {
            //自定义事件,让父组件切换场景0
            this.$emit('changeScene',{scene:0,flag:''})
            //清除数据
            Object.assign(this._data,this.$options.data())
        },
        // table表格复选框按钮的事件
        handleSelectionChange(val){
            //获取到用户选中图片的信息数据，但是需要注意，当前收集的数据当中，缺少isDefault字段
            this.multipleSelection = val;
        },
        //设置默认值的回调
        setDefaultImage(row,$index){
        //排他操作
            this.imageList.forEach((element)=>{
                element.isDefault = 0
            })
            row.isDefault = 1
            //收集到默认显示图片
            this.sku.skuDefaultImg = row.imgUrl
        },
        //确定保存，整理数据、发送请求
        addOrUpdateSku(){
            //1.整理sku属性值[22233:56666]
            // 方式一
            this.attrInfoList.forEach((item)=>{
                    let str =  item.attrIdAndValueId
                    if(str){
                        let index = str.indexOf(":")
                        let attrId = str.substring(0, index);
                        let valueId = str.substring(index+1,str.length)
                        this.sku.skuAttrValueList.push({attrId,valueId})
                        // console.log({attrId,valueId});
                    }
            })
            //方式二 split(":")
             /*    //新建数组
                let arr = [];
                this.attrInfoList.forEach(item=>{
                    //当前平台属性用户进行选择
                    if(item.attrIdAndValueId){
                        const [attrId,valueId] = item.attrIdAndValueId.split(":")
                        let obj = {attrId,valueId}
                        arr.push(obj)
                    }
                })
                //将整理好的参数赋值给this.sku.skuAttrValueList
                this.sku.skuAttrValueList = arr */ 
            //方式三  array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
            /* this.sku.skuAttrValueList = this.attrInfoList.reduce((prev,item)=>{
                if(item.attrIdAndValueId){
                         const [attrId,valueId] = item.attrIdAndValueId.split(":")
                         prev.push({attrId,valueId})
                    }
                return prev;
            },[]) */

            //2.整理sku销售属性值
            this.saleAttrList.forEach((item)=>{
                    let str = item.saleAttrIdAndSaleAttrValueId
                    if(str){
                        let index = str.indexOf(":")
                        let saleAttrId = str.substring(0, index);
                        let saleAttrValueId = str.substring(index+1,str.length)
                        this.sku.skuSaleAttrValueList.push({saleAttrId,saleAttrValueId})
                    }
            })
            
            //3.整理sku图片属性  map()使用为每个数组元素调用函数的结果创建新数组。
            this.sku.skuImageList  = this.multipleSelection.map((currentValue)=>{
                return {
                    imgName:currentValue.imgName,
                    "imgUrl":currentValue.imgUrl,
                    "isDefault":currentValue.isDefault,
                    "spuImgId":currentValue.id
                }
            })
        
            //4. 表单验证通过后,发送添加sku请求
            this.$refs.formSku.validate(async (valid) => {
                if (valid) {
                        const result = await this.$API.sku.reqAddSku(this.sku)
                        if(result.code == 200){
                            this.$message({
                                message: ("添加Sku属性成功"),
                                type: 'success'
                            })
                            //清除数据
                            Object.assign(this._data,this.$options.data()) 
                            this.$emit('changeScene',{scene:0,flag:"success"})
                        }
                } else {
                    console.log('Sku表单验证失败');
                    return false;
                }
                });
        }
    },
    computed:{
            test(){
               console.log("计算属性");
            }
    }
}
</script>

<style scoped>

</style>